import 'dart:io';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:live_music/components/common/RoundUnderlineTabIndicator.dart';
import 'package:live_music/components/common/push_to_refresh_header.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/models/topic_detail_model.dart';
import 'package:live_music/pages/topic/page_view/hot_moment_topic.dart';
import 'package:live_music/pages/topic/page_view/moment_topic.dart';
import 'package:live_music/pages/topic/widget/share_topic.dart';
import 'package:live_music/services/topicService.dart';
import 'package:live_music/utils/cgq_utils.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/oss.dart';
import 'package:live_music/utils/sp_utils.dart';
import 'package:pull_to_refresh_notification/pull_to_refresh_notification.dart';

class TopicDetailPage extends StatefulWidget {
  TopicDetailPage({Key key, this.topicItem}) : super(key: key);
  final TopicDetailModel topicItem;
  @override
  _TopicDetailPageState createState() => _TopicDetailPageState();
}

class _TopicDetailPageState extends State<TopicDetailPage>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  TabController _tabController;
  List<Widget> _tabsContent;
  List<Widget> _tabs;
  DateTime lastRefreshTime = DateTime.now();
  int userId;
  TopicDetailModel topicItem;
  HotMomentTopicWidget _hotMomentTopicWidget;
  MomentTopicWidget _momentTopicWidget;
  double _appBarOpacity = 0;
  @override
  void initState() {
    super.initState();
    if (Get.parameters['name'] != null) {
      getTopicData(Get.parameters['name']);
      _hotMomentTopicWidget =
          HotMomentTopicWidget(topicId: int.parse(Get.parameters['id']));
      _momentTopicWidget =
          MomentTopicWidget(topicId: int.parse(Get.parameters['id']));
    } else {
      setState(() {
        topicItem = widget.topicItem;
      });
      _hotMomentTopicWidget = HotMomentTopicWidget(topicId: topicItem.id);
      _momentTopicWidget = MomentTopicWidget(topicId: topicItem.id);
    }
    _tabsContent = [
      _momentTopicWidget,
      _hotMomentTopicWidget,
    ];
    _tabs = [Text('最新'), Text('热门')];
    _tabController = TabController(
      initialIndex: 0,
      length: _tabs.length,
      vsync: this,
    );
    getData();
  }

  getTopicData(name) async {
    Map<String, dynamic> topicData =
        await TopicService.getTopicDetail({"name": name});
    TopicDetailModel _topicItem = TopicDetailModel.fromJson(topicData['body']);
    setState(() {
      topicItem = _topicItem;
    });
  }

  getData() async {
    Map<String, dynamic> localuserLogin = await SPUtil.getObject('userLogin');
    setState(() {
      userId = localuserLogin['userId'];
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future onRefresh() async {
    if (_tabController.index == 0) {
      await _hotMomentTopicWidget.onRefresh();
    } else if (_tabController.index == 1) {
      await _momentTopicWidget.onRefresh();
    }
  }

  _chooseBgUrl() async {
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.image,
    );
    String bgUrl = await UploadOss.upload(File(result.files.first.path));
    TopicService.updateTopicCoverUrl(
        {"coverUrl": bgUrl, "topicId": topicItem.id});
    setState(() {
      topicItem.coverUrl = bgUrl;
    });
  }

  double maxOffset = 280.0;
  scrollViewDidScrolled(double offSet) {
    double appBarOpacity = offSet / maxOffset;
    if (appBarOpacity < 0) {
      appBarOpacity = 0.0;
    } else if (appBarOpacity > 1) {
      appBarOpacity = 1.0;
    }
    setState(() {
      _appBarOpacity = appBarOpacity;
    });
  }

  //展示分享布局
  void showBottomShare() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true, //可滚动 解除showModalBottomSheet最大显示屏幕一半的限制
        shape: RoundedRectangleBorder(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        backgroundColor: Colors.white,
        builder: (context) {
          return TopicShareWidget(topicItem: topicItem);
        });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        body: RefreshIndicator(
            color: ColorRes.tabLine,
            onRefresh: onRefresh,
            notificationPredicate: (notification) {
              if (notification is ScrollUpdateNotification &&
                  notification.depth == 0) {
                scrollViewDidScrolled(notification.metrics.pixels);
              }
              return true;
            },
            child: ExtendedNestedScrollView(
                onlyOneScrollInBody: true,
                headerSliverBuilder: ((context, innerBoxIsScrolled) {
                  return [
                    SliverAppBar(
                      backgroundColor: Colors.white,
                      pinned: true,
                      expandedHeight: 320,
                      leading: GestureDetector(
                        child: Icon(
                          Icons.arrow_back_ios,
                          size: 20,
                          color: Colors.grey[600],
                        ),
                        onTap: () {
                          if (Get.parameters['id'] != null) {
                            Get.toNamed("/app_page");
                          } else {
                            Get.back();
                          }
                        },
                      ),
                      actions: [
                        userId == topicItem.createUserId
                            ? IconButton(
                                icon: Icon(
                                  Icons.camera_alt,
                                  color: Colors.black54,
                                ),
                                onPressed: _chooseBgUrl,
                              )
                            : Container(),
                        SizedBox(
                          width: 5,
                        ),
                        InkWell(
                          onTap: showBottomShare,
                          child: Container(
                            width: 20,
                            margin: EdgeInsets.only(top: 3),
                            child: Icon(
                              Icons.launch,
                              color: Colors.grey[600],
                              size: 20,
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 5,
                        ),
                      ],
                      centerTitle: true,
                      title: LayoutBuilder(builder: (context, constraints) {
                        return AnimatedOpacity(
                            duration: const Duration(microseconds: 300),
                            opacity: _appBarOpacity,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                SizedBox(
                                    width: 30,
                                    child: CircleAvatar(
                                      radius: 15,
                                      backgroundImage: NetworkImage(
                                        topicItem.coverUrl,
                                      ),
                                    )),
                                SizedBox(
                                  width: 6,
                                ),
                                Text(
                                  "#" + topicItem.name + "#",
                                  style: TextStyle(
                                    color: WcaoTheme.base,
                                    fontSize: 14,
                                  ),
                                ),
                              ],
                            ));
                      }),
                      flexibleSpace: LayoutBuilder(
                        builder: (context, constraints) {
                          double top = constraints.biggest.height;
                          bool isOpacity = top ==
                              MediaQuery.of(context).padding.top +
                                  kToolbarHeight;

                          return FlexibleSpaceBar(
                            centerTitle: true,
                            title: AnimatedOpacity(
                              duration: const Duration(microseconds: 300),
                              opacity: isOpacity ? 1 : 0,
                              child: Text(
                                topicItem.name,
                                style: TextStyle(
                                  color: WcaoTheme.base,
                                  fontSize: WcaoTheme.fsXl,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                            background: Stack(
                              children: [
                                Hero(
                                    tag: topicItem.coverUrl,
                                    child: SizedBox(
                                      width: double.infinity,
                                      child: CgqUtils.imageCache(
                                        topicItem.coverUrl,
                                        fit: BoxFit.cover,
                                      ),
                                    )),
                                Positioned(
                                  child: Container(
                                    color: Colors.black.withOpacity(.33),
                                  ),
                                ),
                                Center(
                                  child: profile(topicItem),
                                )
                              ],
                            ),
                          );
                        },
                      ),
                      bottom:
                          TabBarWidget(tabController: _tabController, tabs: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [Container(), Text('最新')],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [Container(), Text('热门')],
                        ),
                      ]),
                    )
                  ];
                }),
                body: Container(
                    child: ExtendedTabBarView(
                  controller: _tabController,
                  children: _tabsContent,
                )))));
  }

  @override
  bool get wantKeepAlive => true;
}

class TabBarWidget extends StatefulWidget implements PreferredSizeWidget {
  final TabController tabController;
  final List<Widget> tabs;
  TabBarWidget({Key key, this.tabController, this.tabs}) : super(key: key);
  @override
  _TabBarWidgetState createState() => _TabBarWidgetState();
  @override
  Size get preferredSize => Size.fromHeight(44);
}

class _TabBarWidgetState extends State<TabBarWidget>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    double screenWidth = MediaQuery.of(context).size.width;
    return Container(
        width: screenWidth,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15), topRight: Radius.circular(15))),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
                width: 0.35 * screenWidth,
                padding: EdgeInsets.only(top: 15, bottom: 10),
                alignment: Alignment.center,
                child: TabBar(
                  indicatorSize: TabBarIndicatorSize.label,
                  controller: widget.tabController,
                  indicatorColor: ColorRes.tabLine,
                  indicatorWeight: 2,
                  indicator: RoundUnderlineTabIndicator(
                      borderSide: BorderSide(
                    width: 2,
                    color: ColorRes.tabLine,
                  )),
                  unselectedLabelStyle: TextStyle(
                      color: Colors.black, // 下划线颜色
                      fontSize: 14,
                      fontWeight: FontWeight.w600),
                  labelStyle: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w700), //标签文字大小颜色
                  tabs: widget.tabs,
                )),
          ],
        ));
  }

  @override
  bool get wantKeepAlive => true;
}

Widget profile(TopicDetailModel topicItem) {
  return Center(
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          margin: const EdgeInsets.only(top: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                  margin: const EdgeInsets.only(top: 12),
                  width: 250,
                  alignment: Alignment.center,
                  child: Text(
                    "#" + topicItem.name + "#",
                    overflow: TextOverflow.ellipsis,
                    maxLines: 2,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: WcaoTheme.fsXl,
                      fontWeight: FontWeight.bold,
                    ),
                  )),
            ],
          ),
        ),
        Container(
          margin: const EdgeInsets.only(top: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                topicItem.publishTimes.toString() + "个讨论",
                overflow: TextOverflow.ellipsis,
                maxLines: 2,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
      ],
    ),
  );
}
